package com.isxcode.link.plugin.config;

import com.alibaba.fastjson.JSON;
import com.isxcode.link.common.constant.EventTypeConstants;
import com.isxcode.link.common.constant.KafkaConfigConstants;
import com.isxcode.link.common.pojo.dto.LinkData;
import com.isxcode.link.common.pojo.LinkRequest;
import com.isxcode.link.common.pojo.LinkResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.kafka.core.KafkaTemplate;

import java.lang.reflect.Method;
import java.util.Arrays;

/*
 * 处理异步中的异常事件
 *
 * @ispong
 */
@Slf4j
@RequiredArgsConstructor
class AsyncExceptionHandler implements AsyncUncaughtExceptionHandler {

    private final KafkaTemplate<String, String> kafkaTemplate;

    @Override
    public void handleUncaughtException(Throwable throwable, Method method, Object... objects) {

        log.debug("线程异常");
        log.debug("异常信息：" + throwable.getMessage());
        log.debug("方法名字：" + method.getName());
        log.debug("请求参数:" + Arrays.toString(objects));
        LinkRequest linkRequest = JSON.parseObject((JSON.toJSONString(objects[0])), LinkRequest.class);
        log.debug("请求体" + linkRequest.toString());

        // 推送到kafka
        LinkData linkData = LinkData.builder().eventType(EventTypeConstants.THREAD_ERROR_EVENT).build();
        LinkResponse linkResponse = new LinkResponse("500", linkRequest.getExecuteId() + "任务异常:" + throwable.getMessage(), linkData);
        kafkaTemplate.send(KafkaConfigConstants.DEFAULT_TOPIC_NAME, linkRequest.getExecuteId(), JSON.toJSONString(linkResponse));
    }
}
